<?php
//*************Essential libraries****************//
//Singleton pattern implementation
include_once "lib/Singleton.php";
// Exception class
include_once "lib/MTException.php";
// MySQL database setup
//define("DB_HOST", "mysql.helloweb.eu");
define("DB_HOST", "localhost");
//define("DB_USER", "musictalk");
define("DB_USER", "root");
//define("DB_PASSWD", "qweASD7");
define("DB_PASSWD", "");
//define("DB_NAME", "musictalk_db1");
define("DB_NAME", "mt");

include_once "lib/DB/SQL.php";
$mysql = SQL::factory();
try 
{ 
  $mysql->connect(DB_HOST, DB_USER, DB_PASSWD);
  $mysql->query("USE ".DB_NAME." ");
}
catch(MTException $e) { die("DB error"); }

// Session setup
include_once "lib/Session.php";
$session = Session::factory();



if(! $session->isLogged()){
  try{
  	
   //*************FaceBook setup********************//
   require_once 'facebook-platform/client/facebook.php';

   $appapikey = '3c5a4023906347bb3aeb0bceb695803f';
   $appsecret = '998325dd661e64c2434f44dbf1b6ac67';
   $appcallbackurl = 'http://mt.jack/index.php?nokey';
   $facebook = new Facebook($appapikey, $appsecret);
    
    
   $user_id = $facebook->require_login();
   $user = $facebook->api_client->users_getInfo(array($user_id), array('name','pic'));
   $_SESSION[fb_info] = $user[0];
   
   try{
     if(! $session->login($user_id)){
       require_once "models/User.php";
       $user_model = new User_(array(name=>$_SESSION[fb_info]['name'],fb_id=>$user_id,time_added=>'NOW()'));
       $_SESSION[userId] = $user_model->add();
     }
   }catch(MTException $ex){ echo $ex->getDebugMsg(); } 
  }
  catch(Exception $ex){ 	
    try{
      if (!$facebook->api_client->users_isAppAdded()) {
        $session->logout();
        $facebook->redirect($facebook->get_add_url());    
      }
    } 
    catch (Exception $ex) {
      //this will clear cookies for your application and redirect them to a login prompt
      $session->logout();
      $facebook->set_user(null, null);
      //echo $ex->getMessage();
      $facebook->redirect($appcallbackurl);
    }
  }
}
//catch the exception that gets thrown if the cookie has an invalid session_key in it
/*try {
  if (!$facebook->api_client->users_isAppAdded()) {
    $session->logout();
    $facebook->redirect($facebook->get_add_url());    
  }
} catch (Exception $ex) {
  //this will clear cookies for your application and redirect them to a login prompt
  $session->logout();
  $facebook->set_user(null, null);
  //echo $ex->getMessage();
  $facebook->redirect($appcallbackurl);
}*/

//*************Music Talk setup********************//
// Smarty setup
define("SMARTY_DIR", "/usr/share/php/smarty/libs/");
include_once(SMARTY_DIR."Smarty.class.php");

$smarty = new Smarty();
$smarty->template_dir = "views/tpl/";
$smarty->compile_dir = "views/tpl/tpl_c/";
$smarty->config_dir = "views/tpl/config/";
$smarty->cache_dir = "views/tpl/cache/";

//print_r($_SESSION);
?>
